<template>
  <div>
    <a-drawer
      :open="props.open"
      class="custom-class"
      root-class-name="root-class-name"
      :root-style="{ color: 'blue' }"
      title="缴费"
      width="800px"
      placement="right"
      @close="handleClose"
    >
      <a-form layout="inline" :label-col="labelCol" :model="formSate">
        <a-form-item label="小区名称">
          <a-input v-model:value="formSate.village" disabled />
        </a-form-item>
        <a-form-item label="热力卡号">
          <a-input v-model:value="formSate.alipayConsNo" disabled />
        </a-form-item>
        <a-form-item label="用户名称">
          <a-input v-model:value="formSate.holder" disabled />
        </a-form-item>
        <a-form-item label="收费面积">
          <a-input v-model:value="formSate.feeArea" disabled />
        </a-form-item>
        <a-form-item label="收费单价">
          <a-input v-model:value="formSate.price" disabled />
        </a-form-item>
        <a-form-item label="收费期">
          <a-input v-model:value="formSate.year" disabled />
        </a-form-item>
        <!-- <a-form-item label="缴费房间数">
          <a-input :value="formSate.comNameLevel5" disabled />
        </a-form-item> -->
        <a-form-item label="应收全费金额">
          <a-input v-model:value="formSate.normalReceivable" disabled />
        </a-form-item>
        <a-form-item label="应收基本费金额">
          <a-input v-model:value="formSate.heatWasteReceivable" disabled />
        </a-form-item>
        <a-form-item
          label="应收计量费金额"
          v-if="formSate.billingWay == '热量'"
        >
          <a-input v-model:value="formSate.meterFeeReceivable" disabled />
        </a-form-item>
        <a-form-item label="本金拖欠金额">
          <a-input v-model:value="formSate.receivableTotal" disabled />
        </a-form-item>
        <a-form-item label="本金优惠金额">
          <a-input v-model:value="formSate.totalDiscountMoney" disabled />
        </a-form-item>
        <a-form-item label="本金减免金额">
          <a-input v-model:value="formSate.receivableDerate" disabled />
        </a-form-item>
        <a-form-item label="违约金拖欠金额">
          <a-input
            v-model:value="formSate.lateFeeReceivable"
            style="width: 100px"
            disabled
          />
          <a-button
            type="primary"
            :icon="h(EditOutlined)"
            @click="isEdit = true"
          >
            修改
          </a-button>
        </a-form-item>
        <a-form-item label="违约金减免金额">
          <a-input v-model:value="formSate.lateFeeDerate" disabled />
        </a-form-item>
        <a-form-item label="应收金额">
          <a-input v-model:value="formSate.arrearageTotals" disabled />
        </a-form-item>
        <a-form-item label="已收金额">
          <a-input v-model:value="formSate.yjTotal" disabled />
        </a-form-item>
        <a-form-item label="实付基本费" v-if="formSate.billingWay == '热量'">
          <a-input v-model:value="formSate.meterBaseFeearrearage" disabled />
        </a-form-item>
        <a-form-item label="实付计量费" v-if="formSate.billingWay == '热量'">
          <a-input v-model:value="formSate.meterFeearrearage" disabled />
        </a-form-item>
        <a-form-item label="实付本金">
          <a-input v-model:value="formSate.arrearage" disabled />
        </a-form-item>
        <a-form-item label="实付违约金">
          <a-input v-model:value="formSate.arrearageLateFee" disabled />
        </a-form-item>

        <a-form-item label="实际支付金额">
          <a-input v-model:value="formSate.arrearageTotal" type="number" />
        </a-form-item>
        <a-form-item label="缴费人">
          <a-input v-model:value="formSate.holder" />
        </a-form-item>
        <a-form-item label="联系电话">
          <a-input v-model:value="formSate.holdPhone" type="number" />
        </a-form-item>
        <a-form-item label="预收款抵扣">
          <a-radio-group
            v-model:value="formSate.isPrepayAmount"
            :options="plainOptions"
          />
        </a-form-item>
        <a-form-item
          label="账户余额抵扣"
          v-if="formSate.isPrepayAmount === '1'"
        >
          <a-input
            v-model:value="formSate.prepayAmount"
            class="mb-3"
            type="number"
            :max="accountBalance"
            @change="validatePrepayAmount"
          />
          <span style="color: darkgray"
            >账户余额:{{ accountBalance ? accountBalance : 0 }}</span
          >
        </a-form-item>
        <template v-if="showCashFeatures">
          <a-divider orientation="left">抹零功能</a-divider>
          <a-form-item label="抹零">
            <a-radio-group
              v-model:value="formSate.isZero"
              :options="plainOptions"
            />
          </a-form-item>
          <a-form-item label="抹零金额" v-if="formSate.isZero == '1'">
            <a-input
              v-model:value="formSate.zeroAmount"
              class="mb-3"
              type="number"
              @blur="onRadio"
            />
          </a-form-item>
          <a-divider orientation="left">找赎功能</a-divider>
          <a-form-item label="实收现金">
            <a-input
              v-model:value="formSate.cash"
              @blur="onInput"
              type="number"
            />
          </a-form-item>
          <a-form-item label="找赎金额">
            <a-input v-model:value="formSate.smallChange" disabled />
          </a-form-item>
        </template>
        <a-divider orientation="left">支付方式</a-divider>
        <div class="pay-mode-border">
          <div class="pay-mode-container">
            <div
              v-for="item in payMode"
              :key="item.id"
              class="pay-mode-item"
              :class="{
                'pay-mode-item-selected': formSate.selectedPayMode === item.id,
              }"
              @click="handlePayModeSelect(item)"
            >
              <icon-font :type="item.icon" style="font-size: 30px" />
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </a-form>
      <template #footer>
        <div class="drawer-footer">
          <!-- <a-button type="primary" @click="handleClose">取消</a-button> -->
          <a-button
            type="primary"
            :icon="h(AuditOutlined)"
            class="w-full"
            @click="onSubmit"
          >
            提交
          </a-button>
        </div>
      </template>
    </a-drawer>
    <a-modal
      :open="isEdit"
      title="修改违约金"
      @cancel="isEdit = false"
      @ok="onArrearage"
    >
      <a-form layout="inline" :label-col="labelCol" :model="formSate">
        <a-form-item label="实付违约金">
          <div class="flex">
            <a-input v-model:value="formSate.arrearageLateFee" />
            <a-button type="primary" @click="onJisuan">自动计算</a-button>
          </div>
        </a-form-item>
        <a-form-item label="违约金减免金额">
          <a-input v-model:value="formSate.derateNumber" />
        </a-form-item>
        <a-form-item label="违约金拖欠金额">
          <a-input v-model:value="formSate.lateFeeReceivables" disabled />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, h, watch, reactive, computed, onMounted } from "vue";
import { EditOutlined, TrademarkCircleFilled } from "@ant-design/icons-vue";
import { createFromIconfontCN, AuditOutlined } from "@ant-design/icons-vue";
import {
  getAccountBalanceApi,
  submitPayApi,
  updatePenaltyApi,
  getPayInfoApi
} from "#/api/core/charge";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { Decimal } from "decimal.js";
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => ({}),
  },
});
const formSate = ref(props.info);
// 账户余额
const accountBalance = ref(0);

watch(
  () => props.info,
  (newVal) => {
    console.log(newVal);
    formSate.value = { ...newVal };
    formSate.value.isPrepayAmount = "0";
    formSate.value.isZero = "0";
    formSate.value.arrearageTotals = newVal.arrearageTotal;
    getAccountBalanceApi(formSate.value.areaID).then((res: any) => {
      console.log(res);
      accountBalance.value = res.accountBalance ?? 0;
    });
  },
  { deep: true }
);

const IconFont = createFromIconfontCN({
  scriptUrl: "//at.alicdn.com/t/c/font_4920978_1xu5f6tn4o3.js",
});
const isEdit = ref(false);
const payMode = [
  {
    id: 1,
    label: "现金",
    icon: "icon-jinrong-",
  },
  {
    id: 2,
    label: "支票",
    icon: "icon-jinrongchanpinxianxing",
  },
  {
    id: 3,
    label: "转账",
    icon: "icon-zhuanzhang",
  },
  {
    id: 4,
    label: "其他",
    icon: "icon-shouyinji",
  },
  {
    id: 5,
    label: "银行卡",
    icon: "icon-yinhangka",
  },
  {
    id: 6,
    label: "二维码",
    icon: "icon-erweima",
  },
  {
    id: 7,
    label: "扫码盒子",
    icon: "icon-saomahezi",
  },
];

const plainOptions = [
  {
    label: "是",
    value: "1",
  },
  {
    label: "否",
    value: "0",
  },
];
const onRadio = (e: any) => {
  // 只在用户完成输入后（失去焦点时）进行计算
  if (formSate.value.isZero === "1") {
    console.log("计算前金额:", formSate.value.arrearageTotal);
    if (formSate.value.billingWay === "面积") {
      // 获取抹零金额，确保是有效数值
      const zeroAmount = e.target.value
        ? new Decimal(e.target.value)
        : new Decimal(0);
      const originalAmount = new Decimal(formSate.value.arrearageTotal);

      // 计算抹零后的金额，保留两位小数
      const sum = originalAmount.minus(zeroAmount).toFixed(2);
      console.log("计算后金额:", sum);

      // 使用Vue的响应式系统正确更新值
      formSate.value = {
        ...formSate.value,
        arrearageTotal: sum,
        arrearage: new Decimal(sum)
          .minus(formSate.value.arrearageLateFee)
          .toFixed(2),
      };
      console.log("抹零后金额:", sum, "原金额:", originalAmount.toString());
    } else {
      // 获取抹零金额，确保是有效数值
      const zeroAmount = e.target.value
        ? new Decimal(e.target.value)
        : new Decimal(0);
      const originalAmount = new Decimal(formSate.value.arrearageTotal);

      // 计算抹零后的金额，保留两位小数
      const sum = originalAmount.minus(zeroAmount).toFixed(2);
      console.log("计算后金额:", sum);

      // 使用Vue的响应式系统正确更新值
      formSate.value = {
        ...formSate.value,
        arrearageTotal: sum,
        meterBaseFeearrearage: new Decimal(sum)
          .minus(formSate.value.meterFeearrearage)
          .toFixed(2),
      };
    }
  } else {
    //如果选择否就恢复原来的金额
    formSate.value = {
      ...formSate.value,
      arrearageTotal: props.info.arrearageTotal,
      arrearage: props.info.arrearage,
    };
  }
};
const labelCol = { style: { width: "130px" } };
const emit = defineEmits(["update:open", "close"]);
const handleClose = () => {
  emit("close");
};
const onSubmit = () => {
  const data = {
    comID: formSate.value.comID,
    year: formSate.value.year,
    houseID: formSate.value.houseID,
    areaID: formSate.value.areaID,
    jfbzID: formSate.value.jfbzID,
    billingWay: formSate.value.billingWay,
    heatingStatus: formSate.value.heatingStatus,
    tradeDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    realTradeAmount: formSate.value.arrearage,
    tradeWay: formSate.value.tradeWay,
    invoiceWay: "收据",
    payer: formSate.value.holder,
    payerPhone: formSate.value.holdPhone,
    normalReceivable: formSate.value.normalReceivable,
    heatWasteReceivable: formSate.value.heatWasteReceivable,
    lateFeeReceivable: formSate.value.lateFeeReceivable,
    lateFeeRealReceive: formSate.value.arrearageLateFee,
    payUrl: formSate.value.payUrl,
    remark: formSate.value.remark,
    maxTrimZeroMoney: formSate.value.maxTrimZeroMoney,
    zeroAmount: formSate.value.zeroAmount,
    usePrepay: Number(formSate.value.isPrepayAmount),
    prepayAmount: formSate.value.prepayAmount ? formSate.value.prepayAmount : 0,
  };
  console.log(data);
  // 如果实际支付金额为0，提示用户
  if (formSate.value.arrearageTotal == 0) {
    message.warning("实际支付金额不能为0");
    return;
  } else {
    submitPayApi(data).then((res: any) => {
      console.log(res);
      if (res) {
        emit("update:open", false);
        message.success(res);
      }
    });
  }
};
const handlePayModeSelect = (item: any) => {
  formSate.value.selectedPayMode = item.id;
  formSate.value.tradeWay = item.label;
};
const onInput = (e: any) => {
  // 只在用户完成输入后（失去焦点时）进行计算
  // 获取输入的现金金额，确保是有效数值
  const cashAmount = e.target.value
    ? new Decimal(e.target.value)
    : new Decimal(0);

  // 如果选择了预收款抵扣
  if (formSate.value.isPrepayAmount === "1") {
    // 计算扣除预收款后的应付金额
    const prepayAmount = formSate.value.prepayAmount
      ? new Decimal(formSate.value.prepayAmount)
      : new Decimal(0);
    const remainingAmount = new Decimal(formSate.value.arrearageTotal).minus(
      prepayAmount
    );

    // 计算需要找赎的金额
    const smallChange = cashAmount.minus(remainingAmount).toFixed(2);
    formSate.value.smallChange = smallChange;
    console.log("找赎金额(使用预收款):", smallChange);
  } else {
    // 直接计算找赎金额
    const smallChange = cashAmount
      .minus(formSate.value.arrearageTotal)
      .toFixed(2);
    formSate.value.smallChange = smallChange;
    console.log("找赎金额:", smallChange);
  }
};
const showCashFeatures = computed(() => {
  const nonCashPayModes = [2, 3, 5, 7]; // 支票、转账、银行卡、扫码盒子
  return !nonCashPayModes.includes(formSate.value.selectedPayMode);
});

// 验证预收款抵扣金额不超过账户余额
const validatePrepayAmount = (e: any) => {
  const inputValue = parseFloat(e.target.value);
  if (inputValue > accountBalance.value) {
    // 如果输入值大于账户余额，则将值设置为账户余额
    formSate.value.prepayAmount = accountBalance.value;
    // 提示用户
    message.warning(`预收款抵扣金额不能超过账户余额 ${accountBalance.value}`);
  }
};
const onJisuan = () => {
  const sum = new Decimal(formSate.value.arrearageLateFee)
    .minus(formSate.value.derateNumber)
    .toFixed(2);
  if (Number(sum) < 0) {
    message.warning("违约金减免金额不能小于0");
  } else {
    formSate.value.lateFeeReceivables = sum;
  }
};
const onArrearage = async() => {
  const data = {
    areaID:props.info.areaID,
    year:props.info.year,
    derateNumber:formSate.value.derateNumber
  }
  const res = await updatePenaltyApi(data)
  console.log(res)
  if(res){
    message.success(res)
    isEdit.value = false
    const respone = await getPayInfoApi(props.info.areaID,props.info.year)
    formSate.value = { ...respone };
    formSate.value.isPrepayAmount = "0";
    formSate.value.isZero = "0";
    formSate.value.arrearageTotals = respone.arrearageTotal;
  }else{
    message.error("修改违约金失败")
    isEdit.value = false
  }
};
</script>
<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 20px !important;
}
.pay-mode-border {
  width: 100%;
  display: flex;
  justify-content: center;
}
.pay-mode-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.pay-mode-item {
  width: 90px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 1px dashed #1890ff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

/* .pay-mode-item:hover {
  border-color: #006be6;
  color: #006be6;
} */

.pay-mode-item-selected {
  border-color: #006be6;
  /* background-color: #006be6;
  color: #fff; */
  border-style: solid;
}
</style>
